﻿using UnityEngine;
using System.Collections;

public class PlayerDrillShots_Script : MonoBehaviour 
{
	//Public Var
	public float speed;
	public float timeBetweenHits = 0.1f;

	public GameObject LaserGreenHit;
	private GameObject hitObject;

	private enum State {FLYING, DRILLING, DEAD};
	private State state;

	//time since last hit. incremented every FixedUpdate
	//and reset after timeBetweenHits has passed
	private float timeSinceLastHit;

	float distanceFromCamera = 1.0f;

	// Use this for initialization
	void Start ()
	{
		var pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, distanceFromCamera);
		pos = Camera.main.ScreenToWorldPoint(pos);

		Vector3 direction = pos - transform.position;
		direction.z = 0.0f;
		direction.Normalize();

		transform.localRotation = Quaternion.LookRotation(Vector3.forward, direction);
		GetComponent<Rigidbody2D>().velocity = direction * speed;

		state = State.FLYING;
	}



	public void Drill(GameObject other)
	{
		state = State.DRILLING;
		hitObject = other;
		Physics2D.IgnoreCollision(GetComponent<Collider2D>(), other.GetComponent<Collider2D>());
		//GetComponent<Rigidbody2D> ().velocity = other.GetComponent<Rigidbody2D> ().velocity;



		//Vector2 cenas = GetComponent<Rigidbody2D>().GetPointVelocity (other.GetComponent<Rigidbody2D>().worldCenterOfMass);


		//GetComponent<Rigidbody2D> ().
		//set as child of other object
		gameObject.transform.parent = other.transform;
		//gameObject.transform.localPosition =  Vector3.zero; 

		//gameObject.transform = Vector3.zero;
	}

	public void FixedUpdate() {
		if (state == State.DRILLING) {
			timeSinceLastHit += Time.deltaTime;
			if (timeSinceLastHit > timeBetweenHits) {
				timeSinceLastHit -= timeBetweenHits;
				AsteroidScript ast = hitObject.GetComponent<AsteroidScript>();
				ast.hitPoints -=1;
			} 
		}
	}

	void Update()
	{
		if (hitObject) {
			Vector3 toCenter = hitObject.transform.position - transform.position;
			GetComponent<Rigidbody2D> ().velocity =  hitObject.GetComponent<Rigidbody2D>().GetPointVelocity(gameObject.transform.position);
			GetComponent<Rigidbody2D> ().velocity += (new Vector2(toCenter.x, toCenter.y)).normalized * 0.3f;

			//Quaternion q = Quaternion.AngleAxis(angle, Vector3.right);
			//transform.rotation = q;

			GetComponent<Rigidbody2D> ().angularVelocity = hitObject.GetComponent<Rigidbody2D> ().angularVelocity;
		}
		
	}
}
